/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.st.http.server.netty;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;

import com.bambamboo.st.AbstractIOServer;
import com.bambamboo.st.socket.server.SocketConnectionBean;
import com.bambamboo.st.socket.server.netty.AbstractChannelHandler;

/**
 * DOCME
 * 
 * @author tanxuqing
 * @date Dec 24, 2009
 * @since
 */
public class NettyHttpServer extends AbstractIOServer {

    @Override
    public void startup() throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors
                .newCachedThreadPool(), Executors.newCachedThreadPool()));
        ChannelPipeline pipeline = bootstrap.getPipeline();

        // Uncomment the following line if you want HTTPS
        // SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
        // engine.setUseClientMode(false);
        // pipeline.addLast("ssl", new SslHandler(engine));

        pipeline.addLast("decoder", new HttpRequestDecoder());
        // Uncomment the following line if you don't want to handle HttpChunks.
        // pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
        pipeline.addLast("encoder", new HttpResponseEncoder());
        // Remove the following line if you don't want automatic content compression.
        pipeline.addLast("deflater", new HttpContentCompressor());

        SocketConnectionBean bean = (SocketConnectionBean) getConnectionBean();
        AbstractChannelHandler channelHandler = new HttpChannelHandler();
        channelHandler.setConfigurationBean(bean);
        pipeline.addLast("handler", channelHandler);

        // XXX add socket options here? keepAlive

        String port = bean.getPort();
        bootstrap.bind(new InetSocketAddress(Integer.parseInt(port)));
    }

    @Override
    public String getType() {
        return "HTTP";
    }
}
